package oop.ex2.tokenizer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oop.ex2.expression.ExpressionNode;

/**
 * Checks if a certain pattern is found in the beginning of a string.
 * If so, it returns an appropriate Node for the expression tree. This is what connects the syntactical
 * format of the expression with the semantics of the expression tree.
 * 
 * This is the subclass for all of the classes used to analyze as expression string.
 * Any symbol that we want the parser to recognize must be passes to the parser as a specified
 * token analyzer that searches to the correct string.
 * @author daniel_i_l
 *
 */
public abstract class TokenAnalyzer {
	private Pattern _tokenPattern;
	protected String _matchedString;
	public static final String WHITESPACE = "\\s*";
	
	public TokenAnalyzer(String tokenPattern)
	{
		_tokenPattern = Pattern.compile(WHITESPACE + tokenPattern.trim());
	}
	
	/**
	 * Searches the beginning of the line and checks if it can match it to
	 * the tokenPattern.
	 * @param line
	 * @return If the pattern is found, return the index of the last character matched + 1. Otherwise,
	 * return -1.
	 */
	public int getEndOfPatternPosition(String line)
	{
		Matcher tokenMatcher = _tokenPattern.matcher(line);
		
		if (tokenMatcher.lookingAt())
		{
			_matchedString = tokenMatcher.group().trim();
			return tokenMatcher.end();
		}
		
		//if nothing was found
		return -1;
	}
	
	/**
	 * Return an expression node that corresponds to the given token.
	 * 
	 * @return The proper expression node.
	 */
	public abstract ExpressionNode getExpressionNode();
	
}
